// 调用SSO，获取用户的JSON信息串并解析存储session中
const https = require('https');

// 登录验证
exports.checkLogin = (req, cb) => {
  let cookies = {};
  req.headers.cookie &&
    req.headers.cookie.split(';').forEach((cookie) => {
      const parts = cookie.split('=');
      cookies[parts[0].trim()] = (parts[1] || '').trim();
    });

  let hwsso_am = cookies['hwsso_am'];
  let hwsso_login = cookies['hwsso_login'];
  let hwssot = cookies['hwssot'];
  let hwssot3 = cookies['hwssot3'];
  let login_logFlag = cookies['login_logFlag'];
  let login_sid = cookies['login_sid'];
  let login_sip = cookies['login_sip'];
  let login_uid = cookies['login_uid'];
  let LtpaToken = cookies['LtpaToken'];
  let w3Token = cookies['w3Token'];
  let url = 'w3.huawei.com';

  let loginBody = JSON.stringify({
    token: {
      hwsso_am,
      hwsso_login,
      hwssot,
      hwssot3,
      login_logFlag,
      login_sid,
      login_sip,
      login_uid,
      LtpaToken,
      w3Token,
    },
    url,
  });
  if (!hwsso_am) {
    cb(null, null);
  } else {
    let options = {
      host: 'login-beta.huawei.com',
      port: 443,
      rejectUnauthorized: false, // 忽略证书
      path: '/login/rest/token',
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
      },
    };
    let req1 = https.request(options, (res1) => {
      console.log('========= login =========');
      let str = '';
      res1.setEncoding('utf-8');
      res1.on('data', (chunk) => {
        str += chunk;
        let loginuser = JSON.parse(chunk).user;
        // 将用户信息存到session中
        req.session.user = loginuser;
        cb(null, loginuser);
      });
    });
    req1.write(loginBody);
    req1.on('error', (e) => {
      console.log(`exception: ${e.message}`);
    });
    req1.end();
  }
};
